package cn.itcast.consumer.web;

import cn.itcast.consumer.client.UserClient;
import cn.itcast.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private UserClient userClient;

    @GetMapping("{id}")
    public User queryByIdFromUserService(@PathVariable("id") Long id) {
        return userClient.queryUserById(id);
    }

/*
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("{id}")
    public User queryByIdFromUserService(@PathVariable("id") Long id) {
        // 指定serviceId作为主机名即可，Ribbon内部就会帮我根据服务名称拉取服务列表，然后实现负载均衡
        String url = "http://user-service/user/" + id;
        return restTemplate.getForObject(url, User.class);
    }*/
/*
    *//*@HystrixCommand(defaultFallback = "defaultFallbackMethod", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    })*//*
    @HystrixCommand(defaultFallback = "defaultFallbackMethod", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000")
    })
    @GetMapping("{id}")
    public String queryByIdFromUserService(@PathVariable("id") Long id) {
        if(id == 1){
            throw new RuntimeException("我是故意的！");
        }
        // 指定serviceId作为主机名即可，Ribbon内部就会帮我根据服务名称拉取服务列表，然后实现负载均衡
        String url = "http://user-service/user/" + id;
        return restTemplate.getForObject(url, String.class);
    }*/

    public String defaultFallbackMethod(){
        return "不好意思，服务器太忙了！";
    }
/*
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    public User queryByIdFromUserService(@PathVariable("id") Long id) {
        // 拉取服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        // 对服务负载均衡，选出一个服务
        ServiceInstance instance = getInstanceBalance(instances);
        // 获取地址信息
        String host = instance.getHost();
        int port = instance.getPort();

        String url = String.format("http://%s:%d/user/%d", host, port, id);
        return restTemplate.getForObject(url, User.class);
    }

    int count = 0;
    private ServiceInstance getInstanceBalance(List<ServiceInstance> instances) {
     *//*   // 随机
        int index = new Random().nextInt(instances.size());
        return instances.get(index);
        *//*
        // 轮询
        count = (count + 1) % instances.size();
        return instances.get(count);
    }*/
}
